package com.cnjson.sensor.db.service;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;

import com.cnjson.sensor.config.Global;
import com.cnjson.sensor.db.dao.AbstractDao;
import com.cnjson.sensor.db.dao.IDataRecordDao;
import com.cnjson.sensor.db.entity.DataRecord;
import com.cnjson.sensor.db.utils.DaoUtils;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
import org.apache.solr.common.SolrInputDocument;
//import com.cnjson.sensor.nio.SocketServer;

public class DataRecordService extends AbstractDao<DataRecord> implements IDataRecordDao {

//	private static final Logger logger = LoggerFactory.getLogger(SocketServer.class);
	private SolrServer solrServer = new HttpSolrServer(Global.getSolrUrl());

	/*private List<DataRecord> */

	/**
	 * 批量添加采集数据，且导入到索引库中
	 * 
	 * @param records
	 */
	public void addBatch(List<DataRecord> records) throws IOException, SolrServerException {

		StringBuilder sb = new StringBuilder();
		String sDate = getCurrentDate();

		if (records != null && records.size() > 0) {
			sb.append("INSERT INTO ift_data_record(id,equipment_id,channel_NO,check_item_id,processed_data,"
					+ "acquisition_time,reporting_time,del_flag)values");

			String delFlag = "0";
			DataRecord dr = records.get(0);
			delFlag = getDelFlag(dr.getEquipmentId(), dr.getAcquisitionTime());

			for (DataRecord record : records) {
				getSubSql(record, sb, sDate, delFlag);
				sb.append(",");
			}
			sb.setLength(sb.length() - 1);
			sb.append(";");
			/*System.out.println("sql===>" + sb.toString());*/
			this.executeBatch(sb.toString());
			// DataBase.executeBatch(sb.toString());

			sb.setLength(0);
		}

		//添加到索引库中
		//遍历列表将数据逐条加入到document中
		if (records != null) {
			for (DataRecord dataRecord : records) {
				//创建文档对象
				SolrInputDocument document = new SolrInputDocument();
				//添加域 字段和数据
				document.setField("id",dataRecord.getId());
				document.setField("equipment_id",dataRecord.getEquipmentId());

				//关联数据查询
				String sql = "SELECT name From ift_equipment WHERE id = ?";
				Object result = DaoUtils.getValue(sql, dataRecord.getEquipmentId());
				document.setField("equipment_name", result.toString());
				sql = "SELECT scene_id From ift_equipment WHERE id = ?";
				result = DaoUtils.getValue(sql, dataRecord.getEquipmentId());
				document.setField("scene_id",result.toString());
				sql = "SELECT name From ift_check_item WHERE id = ?";
				result = DaoUtils.getValue(sql, dataRecord.getCheckItemId());
				document.setField("check_item_name",result.toString());

				document.setField("channel_NO",dataRecord.getChannelNO());
				document.setField("check_item_id",dataRecord.getCheckItemId());
                sql = "SELECT unit From ift_check_item WHERE id = ?";
                result = DaoUtils.getValue(sql,  dataRecord.getCheckItemId());
				document.setField("unit",result.toString());
				document.setField("processed_data",dataRecord.getProcessedData());
				document.setField("acquisition_time",dataRecord.getAcquisitionTime());
				SimpleDateFormat formattime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				try {
					document.setField("reporting_time",formattime.parse(sDate));
				}catch (Exception e) {
					e.printStackTrace();
				}
				document.setField("is_warning",0);
				document.setField("is_read",0);
				document.setField("is_treatment",0);
				document.setField("warning_reason","");
				//将文档对象写入索引库
				solrServer.add(document);
			}
			//提交
			solrServer.commit();
			System.out.println("添加索引成功-------------------------");
		}
	}

	private void getSubSql(DataRecord record, StringBuilder sb, String sDate, String delFlag) {
		//记录下采集数据的信息
		String id = uuid();
		record.setId(id);
		sb.append("(");
		sb.append("'" + id + "',");
		sb.append("'" + record.getEquipmentId() + "',");
		sb.append("'" + record.getChannelNO() + "',");
		sb.append("'" + record.getCheckItemId() + "',");
		sb.append("'" + record.getProcessedData() + "',");
		// sb.append("'" + record.getDataUnit() + "',");
		String acquisitionTime = sDate;
		try {
			SimpleDateFormat formattime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			acquisitionTime = formattime.format(record.getAcquisitionTime());
		} catch (Exception e) {
		}
		sb.append("'" + acquisitionTime + "',");
		sb.append("'" + sDate + "',");

		sb.append("'" + delFlag + "')");
	}

	private String uuid() {
		return UUID.randomUUID().toString().replaceAll("-", "");
	}

	private String getCurrentDate() {
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String sDate = sdf.format(date);
		return sDate;
	}

	/**
	 * 通过网络地址(设备编码)获取设备ID
	 * 
	 * @param address
	 * @return
	 */
//	public String getEquipmentIdByAddress(String address) {
//		String sql = "Select equipment_id from col_network where location=?";
//		Object ret = DaoUtils.getValue(sql, address);
//		if (ret != null) {
//			return ret.toString();
//		}
//		return address;
//	}
	public String getEquipmentIdByAddress(String address) {
		String sql = "SELECT id From ift_equipment WHERE number = ?";
		Object result = DaoUtils.getValue(sql, address);
		if (result != null)
			return result.toString();
		else
			return null;
	}

	/**
	 * 通过设备ID获取通道对应的检测项目列表数据。 注意通道数据位必须要与实际的检测项目对应起来。
	 *
	 * @param equipmentId
	 * @return
	 */
	public List<Object> getCheckItemIds(String equipmentId, int num) {
		String sql = "SELECT collect_channel_applicate_type_id from ift_equipment_channel a left join ift_equipment b on a.equipment_id=b.id where b.id = ? order by channel_id asc limit "
				+ num;// '" + equipmentId"'
		return DaoUtils.queryFirstColumns(sql, equipmentId);
	}

	@Override
	public DataRecord get(String id) throws Exception {
		DataRecord entity = new DataRecord();
		entity.setId(id);
		return get(entity);
	}

	@Override
	public boolean executeBatch(String sql) {
		return DaoUtils.execute(sql);
	}
	
	/**
	 * 
	 * @param equipmentId
	 * @param date
	 * @return
	 */
	public static String getDelFlag(String equipmentId, Date date) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String sDate = sdf.format(date);
		String sql = "SELECT count(1) from ift_data_record  where equipment_id = ? and acquisition_time = '" + sDate
				+ "'";
		int count = 0;
		try {
			count = Integer.parseInt(DaoUtils.queryFirstColumns(sql, equipmentId).get(0).toString());
		} catch (Exception e) {
			// logger.info("|||||||||||||||||||" + sql);
			// logger.info("|||||||||||||||||||" + count);
		}
		String result = count > 0 ? "1" : "0";
		return result;
	}

}
